#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project : aimix
@File    : clip_worker.py
@IDE     : PyCharm
@Author  : admin
@Date    : 2025/4/14 12:28
"""
import traceback
from worker.base_worker import BaseThread
from core.video.clip import *
from multiprocessing import Process, Queue
from log import log


def do_work(data, progress_queue):
    tasks = []
    channel = data['channel']
    input_files = data['input_files']
    output_folder = data['output_folder']
    arg = data['arg']

    if channel == 'duration':
        for file in input_files:
            tasks.append((file, output_folder, int(arg)))
        func = split_video_by_duration
    elif channel == 'count':
        for file in input_files:
            tasks.append((file, output_folder, int(arg)))
        func = split_video_by_shots
    elif channel == 'voice':
        for file in input_files:
            tasks.append((file, output_folder))
        func = split_video_by_audio
    elif channel == 'scene':
        for file in input_files:
            tasks.append((file, output_folder, float(arg)))
        func = split_video_by_transition
    else:
        return
    with ThreadPoolExecutor(max_workers=5) as executor:
        futures = []
        result = []
        for args in tasks:
            futures.append(executor.submit(func, *args))
            progress_queue.put(2)

        for future in as_completed(futures):
            try:
                result.append(future.result())
            except Exception as e:
                log.error(f"函数 {func.__name__} 运行出错: {e}")
            finally:
                progress_queue.put(2)

    progress_queue.put("done")
    return result


class ClipVideoWorkerThread(BaseThread):
    """分镜视频桥接器"""

    def __init__(self, data, parent=None):
        super(ClipVideoWorkerThread, self).__init__(data, parent)


    def run(self):
        try:
            self.process = Process(target=do_work, args=(self.data, self.queue))
            self.process.start()
            while True:
                msg = self.queue.get()
                if msg == "done":
                    break
                self.on_change_progress(msg)

        except Exception as e:
            traceback.print_exc()
            self.failed.emit(str(e))
        finally:
            self.progress.emit(self.name, 100)